var attachment = [];
var uploadUrl = getContextPath() + "/attachment/upload";
var downloadUrl = getContextPath() + "/attachment/download";
var deleteUrl = getContextPath() + "/attachment/delete";

$(document).ajaxError(function(event, request) {
	if (request.status == 500)
		alert("데이터 저장시 오류 발생!!");
});

var ul = $("<ul></ul>");

// 파일전송 후 콜백 함수
function FileuploadCallback(data, state) {
	var result = $.parseJSON(data);
	if (result.result == "error") {
		alert("파일전송중 에러 발생!!");
		return false;
	}
	addAttachField(result);
	$("#frmFile")[0].reset();
}

function makeFileData(fileName, fileSeq, originalFilename) {
	var data = {
			"fileName" : fileName,
			"fileSeq" : fileSeq,
			"originalFilename" : originalFilename,
			"fileSize" : "0",
			"result" : "success"
	};
	return data;
}

function addAttachField(result) {
	$("<li id='fileSeq" + result.fileSeq + "'>"
			+ urldecode(result.originalFilename)
			+ " 업로드 완료 <a href=\"javascript:fileDelete('"
			+ result.fileSeq
			+ "');\">삭제</a>&nbsp;<a href=\"javascript:toEditor('"
			+ result.fileSeq + "');\">에디터에 붙이기</a></li>").appendTo(ul)
	.appendTo($("#AttachFileListField"));
	$("#fileSeq" + result.fileSeq).data("data", result);
	console.log(result);
	attachment.push(result.fileSeq);
}

function toEditor(fileSeq) {
	var editorContent = getAllEditorContent().content;
	var data = $("#fileSeq" + fileSeq).data("data");
	editorContent = editorContent + "<br /><a href=\"" + downloadUrl
			+ data.fileSeq + "\">" + data.fileName + "</a>";
	gdLoadContent(editorContent, null);
}

function doDeleteAttachmentArray(target) {
	return $.grep(attachment, function(value) {
		return value != target;
	});
}

function fileDelete(target) {
	attachment = doDeleteAttachmentArray(target);
	$("#fileSeq" + target).remove();
	var param = {};
	$.post(deleteUrl + "/" + target, param, function() {
	});
};

$(function() {
	// 비동기 파일 전송
	var frm = $('#frmFile');

	frm.ajaxForm(FileuploadCallback);
	frm.submit(function() {
		return false;
	});
});

// 파일업로드 이벤트
function FileUpload() {
	$("#AttachFileListField").fadeOut(500).delay(500).fadeIn(500);
	if (!$("#Filename").val()) {
		alert("파일을 선택하세요.");
		$("#Filename").focus();
		return;
	}

	// 파일전송
	var frm;
	frm = $('#frmFile');
	frm.attr("action", uploadUrl);
	frm.submit();
}

$(document).ready(function() {
	$("#Filename").change(function() {
		FileUpload();
	});
});
